/*
 * @Author: czy
 * @Date: 2021-04-27 19:30:38
 * @LastEditTime: 2021-07-15 09:20:24
 */
#ifndef __EXCEPTION_H_
#define __EXCEPTION_H_

#include "sys/system.h"
#include "sys/type.h"

typedef struct
{
    unsigned int esp;
    unsigned int ebp;
    unsigned int eip;
    unsigned int edi;
    unsigned int esi;

    unsigned int eflags;

    short int CS;
    short int DS;
    short int ES;
    short int SS;
} jmp_buf;

extern int setjmp(jmp_buf *Jump_Buffer);
extern void longjmp(jmp_buf *Jump_Buffer);

void add_jump_buffer_index(int i);
int get_jump_buffer_index(void);
int get_jump_flags(int index);
void set_jump_flags(int index, int value);
jmp_buf *get_jump_buffer(void);

#define try                                                             \
    add_jump_buffer_index(1);                                           \
    set_jump_flags(get_jump_buffer_index(), setjmp(get_jump_buffer())); \
    if (!get_jump_flags(get_jump_buffer_index()))
#define catch                  \
    add_jump_buffer_index(-1); \
    if (get_jump_flags(get_jump_buffer_index() + 1))
#define throw                                  \
    {                                          \
        int __line__ = __LINE__;               \
        char *__file__ = {__FILE__};           \
        if (get_jump_buffer_index() >= 0)      \
        {                                      \
            longjmp(get_jump_buffer());        \
        }                                      \
        else                                   \
        {                                      \
            printk("Process exit with -1.\n"); \
            processEnd();                      \
        }                                      \
    }
#endif